<?php

namespace common\components;

use common\models\system\SmsRecords;
use Flc\Dysms\Client;
use Flc\Dysms\Request\SendSms;
use backend\models\Config;
use Yii;
use yii\base\Component;

/**
 * Class Message
 * 消息服务
 *
 * @author  Qianlin Zhuang <qianlin.zhuang@gmail.com>
 * @time    2018/11/24 11:44
 * @package common\components
 */
class Message extends Component
{
    /**
     * 大于短信实例
     * @var Client
     */
    public static $sms;

    /**
     * Message constructor.
     */
    public function __construct()
    {
        parent::__construct();
        Yii::$app->params['web'] = Config::lists();

        // 阿里云大于短信配置
        $config = [];
        $config['accessKeyId'] = Yii::$app->params['web']['SMS_ACCESS_KEY'];         // 获取阿里云dySms的accessKeyId
        $config['accessKeySecret'] = Yii::$app->params['web']['SMS_ACCESS_KEY_SECRET']; // 获取阿里云dySms的accessKeySecret

        self::$sms = new Client($config);    // 实例化Client对象
    }

    /**
     * 发送短信
     *
     * ```php
     * Yii::$app->message->sendSms(
     *  ['13793909530','15275786223'],
     *  [
     *      'code' => rand(100000, 999999)
     *  ]
     * );
     *
     * ```
     *
     * @param $mobile   手机号 数组
     * @param $tplCode  短信模板code
     * @param array $templateParam 短信模板参数
     * @return bool|string  ok 成功，其他 失败
     */
    public function sendSms($mobile, $templateParam = [], $type = 1, $userId = 0, $tplCode = '', $signName = '')
    {
        $aliSign = $signName;
        if (empty($aliSign)) {
            $aliSign = Yii::$app->params['web']['SMS_SIGN_NAME'];
        }

        $aliTplCode = $tplCode;
        if (empty($aliTplCode)) {
            $aliTplCode = Yii::$app->params['web']['SMS_TEMPLATE_CODE'];
        }
        $sendSms = new SendSms();
        $sendSms->setPhoneNumbers($mobile);
        $sendSms->setSignName($aliSign);
        $sendSms->setTemplateCode($aliTplCode);
        $sendSms->setTemplateParam($templateParam);
        $sendSms->setOutId('fishingcat');

        $res = self::$sms->execute($sendSms);
        $return = false;
        if (!empty($res->Message)) {

            switch ($res->Code) {
                case 'OK':
                    $return = true;
                    break;
                case 'isv.BUSINESS_LIMIT_CONTROL':
                    $return = '发送太频繁';
                    break;
                case 'isv.MOBILE_NUMBER_ILLEGAL':
                    $return = '非法手机号';
                    break;
                case 'isv.SMS_TEMPLATE_ILLEGAL':
                    $return = '短信模版不合法';
                    break;
                case 'isv.SMS_SIGNATURE_ILLEGAL':
                    $return = '短信签名不合法';
                    break;
                case 'isv.TEMPLATE_MISSING_PARAMETERS':
                    $return = '模版缺少变量';
                    break;
                case 'isv.PARAM_LENGTH_LIMIT':
                    $return = '参数超出长度限制';
                    break;
                case 'isp.SYSTEM_ERROR':
                    $return = '网络异常';
                    break;
                case 'isv.AMOUNT_NOT_ENOUGH':
                    $return = '账户余额不足';
                    break;
                default:
                    break;
            }
        }

// 发送记录
        $noticeRecord = new SmsRecords();
        $noticeRecord->user_id = $userId;
        $noticeRecord->send_account = implode(',', $mobile);
        $noticeRecord->send_status = $return == 'OK' ? 1 : 2;
        $noticeRecord->send_message = !empty($res->Message) ? $res->Message : '';
        $noticeRecord->code = '';
        $noticeRecord->records_type = $type;
        $noticeRecord->created_at = time();

        if (isset($templateParam['code'])) {
            $noticeRecord->code = $templateParam['code'];
        }
        if (!$noticeRecord->save()) {
            $return = '发送失败';
        }

        return $return;
    }

}
